﻿namespace BuzzX8.Xmpp.StreamElements.Factories
{
    public abstract class DatagramElementFactory<TElement, TModel> : StreamElementFactory<TElement, TModel>  where TElement : DatagramElement 
                                                                                                    where TModel : DatagramElementModel
    {
        public IIdGenerator IdGenerator { get; set; }

        protected override void UpdateElementByModel(TElement element, TModel model)
        {
            element.Id = (model.Id == null && IdGenerator != null) ? IdGenerator.GetNewId() 
                                                                   : element.Id = model.Id;
            element.From = model.From;
            element.To = model.To;
            element.XmlLang = model.XmlLang;
            if (model.HasErrorElement) AddErrorElement(element, model.ErrorElementInfo);
        }

        private void AddErrorElement(TElement element, ErrorElementInfo errorElementInfo)
        {
            ErrorElement errorElement = CreateNewErrorElement();
            UpdateErrorElement(errorElement, errorElementInfo);
            element.Elements.Add(errorElement);
        }

        protected abstract ErrorElement CreateNewErrorElement();

        protected void UpdateErrorElement(ErrorElement errorElement, ErrorElementInfo errorElementInfo)
        {
            errorElement.ErrorName = errorElementInfo.Name;
            errorElement.ErrorDescription = errorElementInfo.Description;
            errorElement.DescriptionLang = errorElementInfo.DescriptionLang;
            errorElement.ErrorDetails = errorElementInfo.Details;
        }
    }
}
